package web.eshop;

import org.apache.wicket.extensions.markup.html.captcha.CaptchaImageResource;
import org.apache.wicket.model.LoadableDetachableModel;

public final class CaptchaImageModel extends LoadableDetachableModel<CaptchaImageResource> {

    public CaptchaImageModel(int minChars, int maxChars) {
        this.minChars = minChars;
        this.maxChars = maxChars;
    }

    String imagePass;
    final int minChars;
    final int maxChars;
    CaptchaImageResource captchaImage;

    private int randomInt(int min, int max) {
        return (int) (Math.random() * (max - min) + min);
    }

    private String randomString(int min, int max) {
        int num = randomInt(min, max);
        byte b[] = new byte[num];
        for (int i = 0; i < num; i++) {
            b[i] = (byte) randomInt('a', 'z');
        }
        return new String(b);
    }

    public String getImagePass() {
        return imagePass;
    }

    @Override
    protected CaptchaImageResource load() {
        imagePass = randomString(minChars, maxChars);
        return captchaImage = new CaptchaImageResource(imagePass);
    }
}
